package graph.editor;

import java.util.ArrayList;
import java.util.List;

import observable.ObservableAutomaton;
import automaton.State;
import automaton.StateImpl;
import automaton.Transition;
import automaton.TransitionImpl;
import automaton.TypeState;
import exception.LabelException;
import graph.editor.enhanced.EdgeModified;
import graph.editor.enhanced.VertexModified;

/**
 * @opt nodefillcolor green
 * @opt attributes
 * @opt operations
 * @depend - - - automaton.State
 * @depend - - - graph.editor.Vertex
 * @depend - - - automaton.Transition
 * @depend - - - exception.LabelException
 * @depend - - - automaton.TypeState
 */
public class DataToAutomaton {

	private 		List<EdgeModified>  edges;
	private static  State[] 			states = new State[]{new StateImpl(true, false), new StateImpl(false, true), new StateImpl(true, true), new StateImpl(false, false)};
	
	public DataToAutomaton(List<EdgeModified> edges){
		this.edges = edges;
	}
	
	public ObservableAutomaton<String> getObservableAutomaton() throws LabelException{		
		List<Transition<String>> transitions 	= new ArrayList<Transition<String>>();
		ObservableAutomaton<String> automate 	= null;
		for(EdgeModified edge : edges){
			if(edge.getText() == null || edge.getText().equals("")){
				throw new LabelException(edge);
			}
			State 	source 	= getState((VertexModified) edge.v1);
			State 	target 	= getState((VertexModified) edge.v2);
			String 	label	= edge.getText();
			transitions.add(new TransitionImpl<String>(source, target, label));
		}
		try{
			Transition<String>[] transitionList = transitions.toArray(new Transition[transitions.size()]);
			
			automate = new ObservableAutomaton<String>(transitionList);
		} catch (Exception e) {
			System.err.println("Warning an error occured!");
			System.err.println("Message: "+e.getMessage());
			System.err.println("Trace: "+e.getStackTrace());
		}

		return automate;
	}

	public static State getState(VertexModified vertex){
		State state =  null;
		TypeState typeState = vertex.getState();
		switch(typeState){
		case INITIAL:
			state = states[0];
			break;
		case FINAL:
			state = states[1];
			break;
		case INITIAL_AND_FINAL:
			state = states[2];
			break;
		case INTERMEDIATE:
			state = states[3];
			break;
		}
		return state;
	}
}
